import { defineStore } from 'pinia';

import appConfig from '@/data/config.json';
import http from '@/util/request';
import apiCommon from '@/api/common';
import { userAgent } from '@/util/common';
// 定义 Store
export const useAppStore = defineStore('app', {
    state: () => ({
        tenantId: '',
        showNavbar: true,
        pageAfterLogin: '',
    }),
    getters: {},
    actions: {
        async init() {
            this.showNavbar = !(userAgent.isWeiXin || userAgent.isDingTalk);
            await this.refreshTenantId();
        },
        //刷新租户id
        refreshTenantId() {
            return new Promise((resolve, reject) => {
                let tenantId: string = this.tenantId;
                if (!tenantId) {
                    let domain: string = http.config.baseURL || '';
                    if (domain.startsWith('https')) {
                        domain = appConfig.domain;
                    }
                    apiCommon
                        .getTenantByDomainArray({
                            domainArray: domain.replace(/^https?\:\/\//i, ''),
                        })
                        .then((res: any) => {
                            uni.setNavigationBarTitle({
                                title: res.data2.productName,
                            });
                            this.tenantId = res.data;
                            console.log(this.tenantId);
                            resolve(null);
                        })
                        .catch((e: any) => {
                            reject(e);
                        });
                } else {
                    resolve(null);
                }
            });
        },
        setPageAfterLogin(data: string) {
            this.pageAfterLogin = data;
        },
    },
    // 网页端配置
    // persist: true,
    // 小程序端配置
    persist: {
        storage: {
            getItem(key) {
                return uni.getStorageSync(key);
            },
            setItem(key, value) {
                uni.setStorageSync(key, value);
            },
        },
    },
});
